/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 * 
 * PremisesServiceImpl.java
 */
package com.yixun.qfbao.xf.service.impl;

import com.yixun.common.page.Page;
import com.yixun.qfbao.constant.RedisKeyConstant;
import com.yixun.qfbao.constant.StringConstant;
import com.yixun.qfbao.mapper.AreaMapper;
import com.yixun.qfbao.mapper.CommissionRulesMapper;
import com.yixun.qfbao.mapper.CompanyMapper;
import com.yixun.qfbao.mapper.EstateAdviserMapper;
import com.yixun.qfbao.model.*;
import com.yixun.qfbao.model.dto.AreaDto;
import com.yixun.qfbao.model.dto.CommissionRulesDto;
import com.yixun.qfbao.model.dto.CompanyDto;
import com.yixun.qfbao.model.enums.*;
import com.yixun.qfbao.service.BaseCodeValueService;
import com.yixun.qfbao.util.CityGroupUtils;
import com.yixun.qfbao.util.DateStyle;
import com.yixun.qfbao.util.DateUtils;
import com.yixun.qfbao.util.RedisUtil;
import com.yixun.qfbao.util.StringUtil;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.mapper.PremisesMapper;
import com.yixun.qfbao.xf.model.CaseMember;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.*;
import com.yixun.qfbao.xf.model.enums.*;
import com.yixun.qfbao.xf.service.CaseMemberService;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * [文件名称]<br>
 * PremisesServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 * 楼盘信息 service interface impl<br>
 * <br>
 * [修改记录]<br>
 * 2015-10-14 15:34:13 创建 陶俊代码生成器<br>
 * 
 * @author 陶俊代码生成器
 * @version 1.00
 */
@Service("premisesService")
public class PremisesServiceImpl implements PremisesService {

	@Autowired
	private PremisesMapper mapper;

	@Autowired
	private AreaMapper areaMapper;

	@Autowired
	private CompanyMapper companyMapper;

	@Autowired
	private CommissionRulesMapper commissionRulesMapper;

	@Autowired
	private BaseCodeValueService baseCodeValueService;

	@Autowired
    private CaseMemberService caseMemberService;

	@Autowired
	private EstateAdviserMapper estateAdviserMapper;

	public static final String REG = ",";

	private static final Logger LOGGER = LoggerFactory.getLogger(PremisesServiceImpl.class);
	
	/**
	 * @param entity
	 *            搜索条件
	 * @param begin
	 *            分页开始行数[不包含]
	 * @param end
	 *            分页结束行数[包含]
	 * @return 分页记录
	 */
	@Transactional(readOnly = true)
	@Override
	public Page<Premises> getPageModel(PremisesDto entity, int begin, int end) {
		Integer total = mapper.count(entity);
		List<Premises> rows = mapper.list(entity, begin, end);

		Set<Long> areaIds = new HashSet<Long>();
		List<Long> companyIds = new ArrayList<Long>();
		if (null != rows && rows.size() > 0) {
			for (Premises p : rows) {
				areaIds.add(p.getAreaId());
				companyIds.add(p.getCompanyId());
			}
		}
		// 查询城区，公司
		Map<Long, Area> areaMap = new HashMap<Long, Area>();
		Map<Long, Company> companyMap = new HashMap<Long, Company>();
		CompanyDto cdto = new CompanyDto();
		cdto.setIds(companyIds);
		cdto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<CompanyDto> companies = companyMapper.selectListByIds(cdto);
		List<Area> areas = areaMapper.selectWithIds(areaIds);
		if (companies != null && companies.size() > 0) {
			companyMap = companies.stream().collect(Collectors.toMap(CompanyDto::getId, a -> a, (k1, k2) -> k1));
		}

		if (areas != null && areas.size() > 0) {
			areaMap = areas.stream().collect(Collectors.toMap(Area::getId, a -> a, (k1, k2) -> k1));
		}

		// 查询城市
		if (null != rows && rows.size() > 0) {
			for (Premises premises : rows) {
				Area area = areaMap.get(premises.getAreaId());
				premises.setArea(area == null ? new Area() : area);
				if (area != null) {
					premises.setFullAreaName(area.getFullName());
				}
				premises.setPremisesStatusCN(PremisesStatusEnum.getByNo(premises.getPremisesStatus()).getDes());
				// 查询商户
				Company company = companyMap.get(premises.getCompanyId());
				premises.setCompanyName(company == null ? "" : company.getCompanyName());
			}
		}

		Page<Premises> msr = new Page<Premises>(total, rows);
		return msr;
	}

	@Override
	public Page<PremisesDto> getPageModelByAcreage(PremisesDto entity, int begin, int end) {
		Integer total = mapper.countByAcreage(entity);
		List<PremisesDto> rows = mapper.listByAcreage(entity, begin, end);
		return setPremisesPage( rows, total, begin, end, null);

	}
	
	@Override
	public Page<PremisesDto> getPremisesIncludeAttetion(PremisesDto entity, int begin, int end) {
		List<PremisesDto> rows = mapper.getPremisesIncludeAttetion(entity, begin, end);
		return setPremisesPage(rows, 0, begin, end, "7");
	}
	
	@Override
	public Page<PremisesDto> getPageModelForHistory(PremisesDto entity, int begin, int end){
		Integer total = mapper.countByPremisesHistory(entity);
		List<PremisesDto> rows = mapper.listByPremisesHistory(entity, begin, end);
		return setPremisesPage( rows, total, begin,  end, null);
	}
	private Page<PremisesDto> setPremisesPage(List<PremisesDto> rows,Integer total,int begin, int end, String systemId){
		
		List<Long> areaIds = new ArrayList<>();
		List<Long> companyIds = new ArrayList<>();
		List<Long> premisesIds =new ArrayList<>();
		Map<Long, Area> areaMap = new HashMap<>();
		Map<Long, Company> companyMap = new HashMap<>();

		if(CollectionUtils.isEmpty(rows)){
			return new Page<>(total, rows);
		}

		for (PremisesDto premises : rows) {
			Long areaId = premises.getAreaId();
			Long provId = premises.getProvinceId();
			Long cityId = premises.getCityId();
			Long premisesId = premises.getId();
			areaIds.add(provId);
			areaIds.add(cityId);
			premisesIds.add(premisesId);

			if (areaId == null) {
				areaId = premises.getCityId();
			}
			areaIds.add(areaId);
			Long companyId = premises.getCompanyId();
			if (companyId != null) {
				companyIds.add(companyId);
			}
		}


		// 查询各个集合
		AreaDto areaDto = new AreaDto();
		areaDto.setIds(areaIds);
		List<Area> areas = areaMapper.selectListByDto(areaDto);
		for (Area a : areas) {
			areaMap.put(a.getId(), a);
		}
		
		CompanyDto companyDto = new CompanyDto();
		companyDto.setIds(companyIds);
		List<CompanyDto> companies = companyMapper.selectListByIds(companyDto);
		for (Company c : companies) {
			companyMap.put(c.getId(), c);
		}

		CaseMemberDto cmDto = new CaseMemberDto();
		cmDto.setPremisesIds(premisesIds);
		cmDto.setPiStatus(MechanismStatusEnum.enable.getNo());
		cmDto.setOrders("t.create_time desc");
		List<CaseMemberDto> cmDtoList = caseMemberService.selectCMListGroupByPremises(cmDto);
		Map<Long, List<CaseMemberDto>> cmDtoMap = cmDtoList.stream().collect(Collectors.groupingBy(CaseMemberDto::getPremisesId));

		// 查询城市
		if (null != rows && rows.size() > 0) {
			for (PremisesDto premises : rows) {
				Long areaId = premises.getAreaId();
				Long provId = premises.getProvinceId();
				Long cityId = premises.getCityId();
				if (areaId == null) {
					areaId = premises.getCityId();
				}else {
					premises.setAreaName(areaMap.get(areaId) == null? null: areaMap.get(areaId).getName());
				}
				if(provId != null) {
					premises.setProvinceName(areaMap.get(provId) == null? null: areaMap.get(provId) .getName());
				}
				if(cityId != null) {
					premises.setCityName(areaMap.get(cityId) == null? null: areaMap.get(cityId) .getName());
				}
				if (areaId != null) {
					Area area = areaMap.get(areaId);
					if (area != null) {
						premises.setArea(area);
						premises.setFullAreaName(area.getFullName());
					} else {
						premises.setArea(new Area());
					}
				}
				if(SystemIdEnum.WEAPP_AGENCY.getCode().equals(systemId)) {
					//如果是分销小程序，则不需要设置下面的信息
					LOGGER.info("分销小程序，查询结束");
					continue;
				}
				premises.setPremisesStatusCN(PremisesStatusEnum.getByNo(premises.getPremisesStatus()).getDes());
				// 查询商户
				Company company = companyMap.get(premises.getCompanyId());
				premises.setCompanyName(company == null ? "" : company.getCompanyName());

				//获取驻守人员手机号
				// 楼盘驻守人员(取一人)
                cmDtoList = cmDtoMap.get(premises.getId());
				if(CollectionUtils.isNotEmpty(cmDtoList)){
                    premises.setCaseMemberName(StringUtils.defaultIfBlank(cmDtoList.get(0).getAccountName(), ""));
                    premises.setCaseMemberPhone(StringUtils.defaultIfBlank(cmDtoList.get(0).getPhone(), ""));
                    for (CaseMemberDto dto : cmDtoList) {
                        if("1".equals(dto.getPhoneStatus())){
                            premises.setCaseMemberName(StringUtils.defaultIfBlank(dto.getAccountName(), ""));
                            premises.setCaseMemberPhone(StringUtils.defaultIfBlank(dto.getPhone(), ""));
                        }
                    }
                }
			}
		}

		Page<PremisesDto> resPage = new Page<>();
		resPage.setRows(rows);
		resPage.setPageInfo(total, begin, begin + end);
		return resPage;
	}
	/**
	 * @param entity
	 *            搜索条件
	 * @param begin
	 *            分页开始行数[不包含]
	 * @param end
	 *            分页结束行数[包含]
	 * @return 分页记录
	 */
	@Transactional(readOnly = true)
	@Override
	public Page<Premises> getPageModelByArea(PremisesDto entity, int begin, int end) {
		Integer total = mapper.countByArea(entity);
		List<Premises> rows = mapper.listByArea(entity, begin, end);
		// 查询城市
		if (null != rows && rows.size() > 0) {
			for (Premises premises : rows) {
				Long areaId = premises.getAreaId();
				if (areaId == null) {
					areaId = premises.getCityId();
				}
				if (areaId != null) {
					Area area = areaMapper.selectById(areaId);
					if (area != null) {
						premises.setArea(area);
						premises.setFullAreaName(area.getFullName());
					} else {
						premises.setArea(new Area());
					}
				}
				premises.setPremisesStatusCN(PremisesStatusEnum.getByNo(premises.getPremisesStatus()).getDes());
				// 查询商户
				Company company = companyMapper.selectById(premises.getCompanyId());
				premises.setCompanyName(company == null ? "" : company.getCompanyName());
			}
		}

		Page<Premises> msr = new Page<Premises>(total, rows);
		return msr;
	}

	@Override
	public List<Premises> selectListByDto(PremisesDto entity) {
		return mapper.selectListByDto(entity);
	}

	@Override
	public List<Premises> selectListByDto2(PremisesDto entity) {
		return mapper.selectListByDto2(entity);
	}

	@Override
	public List<Premises> selectSimpleListByDto(PremisesDto entity) {
		return mapper.selectSimpleListByDto(entity);
	}

	@Override
	public List<Premises> selectMyListByDto(PremisesDto entity) {
		return mapper.selectMyListByDto(entity);
	}


	/**
	 * 查询列表
	 * 
	 * @param entity
	 *            搜索条件
	 * @return 分页记录
	 */
	@Override
	public List<Premises> selectLpInfo(PremisesDto entity) {
		return mapper.selectLpInfo(entity);
	}

	/**
	 * 查询单个
	 * 
	 * @param entity
	 *            搜索条件
	 * @return 分页记录
	 */
	@Override
	public Premises selectByDto(PremisesDto entity) {
		return mapper.selectByDto(entity);
	}

	/**
	 * @param id
	 *            搜索条件
	 * @return 分页记录
	 */
	@Override
	public Premises selectById(Long id) {
		if (id != null) {
			return mapper.selectById(id);
		}
		return null;
	}

	@Override
	public Premises selectSimpleById(Long id) {
		if (id != null) {
			return mapper.selectSimpleById(id);
		}
		return null;
	}

	/**
	 * 特殊需求
	 * 
	 * @param premisesId
	 * @return
	 */
	@Override
	public Premises selectById2(Long premisesId) {
		return mapper.selectById2(premisesId);
	}

	/**
	 * @param entity
	 *            新增记录的详细信息
	 * @return 新增行数
	 */
	@Override
	public PremisesDto create(PremisesDto entity) {
		entity.setCreateTime(Calendar.getInstance().getTime());
		entity.setUpdateTime(Calendar.getInstance().getTime());
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		int count = mapper.add(entity);
		if(count > 0 && StringUtils.isNotBlank(entity.getReportWay())){
			String premisesReportWayKey = RedisKeyConstant.Premises.PREMISES_REPORT_WAY_ + entity.getId();
			RedisUtil.set(premisesReportWayKey, entity.getReportWay());
		}
		return entity;
	}

	/**
	 * @param entity
	 *            更新记录的详细信息
	 * @return 更新行数
	 */
	@Override
	public int update(PremisesDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		if(StringUtils.isNotBlank(entity.getReportWay())){
			String premisesReportWayKey = RedisKeyConstant.Premises.PREMISES_REPORT_WAY_ + entity.getId();
			RedisUtil.set(premisesReportWayKey, entity.getReportWay());
		}
		return mapper.edit(entity);
	}

    @Override
    public int updateByPrimaryKey(PremisesDto entity) {
        entity.setUpdateTime(Calendar.getInstance().getTime());
		if(StringUtils.isNotBlank(entity.getReportWay())){
			String premisesReportWayKey = RedisKeyConstant.Premises.PREMISES_REPORT_WAY_ + entity.getId();
			RedisUtil.set(premisesReportWayKey, entity.getReportWay());
		}
        return mapper.updateByPrimaryKey(entity);
    }

    /**
	 * @param entity
	 *            待删除的记录信息
	 * @return 删除行数
	 */
	@Override
	public int destroy(PremisesDto entity) {
		if(Objects.nonNull(entity.getId())){
			String premisesReportWayKey = RedisKeyConstant.Premises.PREMISES_REPORT_WAY_ + entity.getId();
			RedisUtil.delete(premisesReportWayKey);
		}
		return mapper.del(entity);
	}

	/**
	 * @param entity
	 *            新增或更新
	 * @return 新增行数
	 */
	@Override
	public int saveOrUpdate(PremisesDto entity) {
		if (entity != null && entity.getId() != null) {
			return update(entity);
		} else {
			create(entity);
			return 1;
		}
	}

	/**
	 * @param entity
	 *            根据pojo搜索如果主键为空则返回它本身
	 * @return 一行记录或本身
	 */
	@Override
	public Premises selectBy(Premises entity) {
		if (entity != null && entity.getId() != null) {
			return mapper.selectById(entity.getId());
		}
		return entity;
	}

	@Override
	public List<Premises> findList(PremisesDto entity) {
		List<Premises> premisesList = mapper.selectListByDto(entity);
		if (premisesList != null && premisesList.size() > 0) {
			for (Premises premises : premisesList) {
				Area area = areaMapper.selectById(premises.getAreaId());
				premises.setArea(area == null ? new Area() : area);
				premises.setFullAreaName(area.getFullName());
				premises.setPremisesStatusCN(PremisesStatusEnum.getByNo(premises.getPremisesStatus()).getDes());
				// 查询商户
				Company company = companyMapper.selectById(premises.getCompanyId());
				premises.setCompanyName(company == null ? "" : company.getCompanyName());
			}
		}
		return premisesList;
	}

	@Override
	public List<ZPremisesDto> selectPremisesCityListByDto(PremisesDto entity) {
		return mapper.selectPremisesCityListByDto(entity);
	}

	@Override
	public int delete(PremisesDto entity) {
		if(Objects.nonNull(entity.getId())){
			String premisesReportWayKey = RedisKeyConstant.Premises.PREMISES_REPORT_WAY_ + entity.getId();
			RedisUtil.delete(premisesReportWayKey);
		}
		return mapper.del(entity);
	}

	/**
	 * @param entity
	 *            搜索条件
	 * @param begin
	 *            分页开始行数[不包含]
	 * @param end
	 *            分页结束行数[包含]
	 * @return 分页记录
	 */
	@Transactional(readOnly = true)
	@Override
	public Page<Premises> findPremisesByPartnerModel(PremisesDto entity, int begin, int end) {
		Integer total = mapper.findPremisesByPartnerCount(entity);
		List<Premises> rows = mapper.findPremisesByPartnerList(entity, begin, end);
		// 查询楼盘关联关系
		Set<Long> areaIds = new HashSet<Long>();
		List<Long> companyIds = new ArrayList<Long>();
		if (null != rows && rows.size() > 0) {
			for (Premises p : rows) {
				areaIds.add(p.getAreaId());
				companyIds.add(p.getCompanyId());
			}
		}
		// 查询城区，公司
		Map<Long, Area> areaMap = new HashMap<Long, Area>();
		Map<Long, Company> companyMap = new HashMap<Long, Company>();
		CompanyDto cdto = new CompanyDto();
		cdto.setIds(companyIds);
		cdto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<CompanyDto> companies = companyMapper.selectListByIds(cdto);
		List<Area> areas = areaMapper.selectWithIds(areaIds);
		if (companies != null && companies.size() > 0) {
			companyMap = companies.stream().collect(Collectors.toMap(CompanyDto::getId, a -> a, (k1, k2) -> k1));
		}

		if (areas != null && areas.size() > 0) {
			areaMap = areas.stream().collect(Collectors.toMap(Area::getId, a -> a, (k1, k2) -> k1));
		}
		// 查询城市
		if (null != rows && rows.size() > 0) {
			for (Premises premises : rows) {
				Area area = areaMap.get(premises.getAreaId());
				premises.setArea(area == null ? new Area() : area);
				if (area != null) {
					premises.setFullAreaName(area.getFullName());
				}
				if (StringUtils.isNotEmpty(premises.getPremisesStatus())) {
					premises.setPremisesStatusCN(PremisesStatusEnum.getByNo(premises.getPremisesStatus()).getDes());
				}

				if (StringUtils.isNotEmpty(premises.getCommissionWay())) {
					premises.setCommissionWay(CommissionWayEnum.getDescByNo(premises.getCommissionWay()));
				}
				// 查询商户
				Company company = companyMap.get(premises.getCompanyId());
				premises.setCompanyName(company == null ? "" : company.getCompanyName());
			}
		}

		Page<Premises> msr = new Page<Premises>(total, rows);
		msr.setPageInfo(total, begin, begin + end);
		msr.setPageSize(end);
		return msr;
	}

	/**
	 * 查询列表
	 * 
	 * @param entity
	 *            搜索条件
	 * @return 分页记录
	 */
	@Override
	public List<Premises> listByName(PremisesDto entity) {
		return mapper.listByName(entity);
	}

	@Override
	public List<Premises> selectPremisesList(PremisesDto entity) {

		return mapper.selectPremisesList(entity);
	}

	/**
	 * @Description: 获取已设置佣金规则的楼盘列表
	 * @Author: guifang.weng
	 * @Date: 2017/10/19
	 **/
	@Override
	public Map<String, Object> getPremisesList(PremisesDto premisesDto) throws TServerException {
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		List<PremisesDto> list = mapper.selectPremisesListWithRule(premisesDto);
		if (list != null && list.size() > 0) {
			for (PremisesDto dto : list) {
				resultMap.put(String.valueOf(dto.getId()), dto.getName());
			}
		}
		return resultMap;
	}

	@Override
	public Page<PremisesDto> selectPremisesPageListWithRule(PremisesDto premisesDto, int begin, int end,String accountType,Long caseMemberId)
			throws TServerException {
		int total = 0;
		List<PremisesDto> list = null;
		if("0".equals(accountType)){
			total = mapper.selectPremisesPageListCountWithRule(premisesDto);
			list = mapper.selectPremisesPageListWithRule(premisesDto, begin, end);
		}else{
			total = mapper.selectPremisesPageListCountWithRuleForCaseMember(premisesDto,caseMemberId);
			list = mapper.selectPremisesPageListWithRuleForCaseMember(premisesDto, caseMemberId, begin, end);
		}

		if (list != null && list.size() > 0) {
			for (PremisesDto dto : list) {
				CommissionRulesDto cr = new CommissionRulesDto();
				cr.setGroupId(dto.getGroupId());
				cr.setDelFlag(DelFlagEnum.UNDEL.getNo());
				cr.setOrders(" t.id asc");
				List<CommissionRules> ruleList = commissionRulesMapper.selectListByDto(cr);
				if (ruleList != null && ruleList.size() > 0) {
					StringBuffer ruleStr = new StringBuffer();
					String rule = "";
					String rate = "";
					String type = "";
					String sort = "";
					String[] ruleArr = {};
					for (CommissionRules commissionRules : ruleList) {
						type = commissionRules.getCommissionType();
						rate = commissionRules.getCommissionRate();
						sort = commissionRules.getSort();
						rule = commissionRules.getRule();
						if (StringUtils.isNotBlank(rule)) {
							ruleArr = rule.split(",");
							if (CommisionModeEnum.COMMISION_MODE_3.getNo().equals(type)) {
								if ("1".equals(sort)) {
									// 这里的判断是因为数据[,10]有时候分割出来的是{10}，有时候分割出来的是{，10}。原因暂不明
									if (ruleArr.length > 1) {
										ruleStr.append(ruleArr[1] + "套以下，佣金比例为" + rate + "%;");
									} else {
										ruleStr.append(ruleArr[0] + "套以下，佣金比例为" + rate + "%;");
									}
								} else if ("2".equals(sort)) {
									ruleStr.append(ruleArr[0] + "-" + ruleArr[1] + "套，佣金比例为" + rate + "%;");
								} else if ("3".equals(sort)) {
									ruleStr.append(ruleArr[0] + "套以上，佣金比例为" + rate + "%");
								}
							} else if (CommisionModeEnum.COMMISION_MODE_4.getNo().equals(type)) {
								if ("1".equals(sort)) {
									if (ruleArr.length > 1) {
										ruleStr.append(ruleArr[1] + "元以下，佣金比例为" + rate + "%;");
									} else {
										ruleStr.append(ruleArr[0] + "元以下，佣金比例为" + rate + "%;");
									}
								} else if ("2".equals(sort)) {
									ruleStr.append(ruleArr[0] + "-" + ruleArr[1] + "元，佣金比例为" + rate + "%;");
								} else if ("3".equals(sort)) {
									ruleStr.append(ruleArr[0] + "元以上，佣金比例为" + rate + "%");
								}
							}
						} else {
							if (CommisionModeEnum.COMMISION_MODE_1.getNo().equals(type)) {
								ruleStr.append(commissionRules.getCommissionAmmount());
							} else if (CommisionModeEnum.COMMISION_MODE_2.getNo().equals(type)) {
								ruleStr.append(commissionRules.getCommissionRate() + "%");
							}
						}
						dto.setCommissionRuleStr(ruleStr.toString());
					}
				}
				// todo 非空判断
				if (StringUtils.isNotBlank(dto.getState())) {
					String state = CommisionStateEnum.getByNo(dto.getState()).getDes();
					dto.setStateStr(state);
				}
				if (StringUtils.isNotBlank(dto.getCommissionMode())) {
					String modeStr = CommisionModeEnum.getByNo(dto.getCommissionMode()).getDes();
					dto.setCommissionModeStr(modeStr);
				}

			}
		}
		Page<PremisesDto> page = new Page<PremisesDto>(total, list);
		return page;
	}

	/*
	 * 查询开发商佣金设置楼盘列表 楼盘管理中已审核通过，在售的楼盘
	 * 
	 * @author sangtao
	 * 
	 * @return
	 */
	@Override
	public List<Premises> getListForCommissionRule(Long companyId,String accountType,Long partnerId) {
		if (companyId == null) {
			throw new RuntimeException("开发商id为空");
		}
		PremisesDto entity = new PremisesDto();
		// 审核通过
		entity.setPremisesStatus(PremisesStatusEnum.type1.getNo());
		// 在售
		entity.setSaleStatus(SaleStatusEnum.type_1.getNo());
		// 开发商
		entity.setCompanyId(companyId);
		if("0".equals(accountType)){
			return mapper.selectListByDtoWithQuick(entity);
		}else{
			//非管理员返回驻守的楼盘
			if(partnerId != null){
				return mapper.selectCaseMemberPremises(entity,partnerId);
			}else{
				throw new RuntimeException("未获取到用户信息");
			}

		}

	}

	@Override
	public List<Premises> getListModelByAcreage(PremisesDto entity) {
		List<Premises> rows = mapper.getListByAcreage(entity);

		List<Long> areaIds = new ArrayList<Long>();
		List<Long> companyIds = new ArrayList<Long>();
		Map<Long, Area> areaMap = new HashMap<Long, Area>();
		Map<Long, Company> companyMap = new HashMap<Long, Company>();

		// 查询优化
		if (null != rows && rows.size() > 0) {
			for (Premises premises : rows) {
				Long provId = premises.getProvinceId();
				Long areaId = premises.getAreaId();
				Long cityId = premises.getCityId();
//				if (areaId == null) {
//					areaId = premises.getCityId();
//				}
				if(provId != null && !areaIds.contains(provId)) {
					areaIds.add(provId);
				}
				if(cityId != null && !areaIds.contains(cityId)) {
					areaIds.add(cityId);
				}
				if(areaId != null && !areaIds.contains(areaId)) {
					areaIds.add(areaId);
				}
				Long companyId = premises.getCompanyId();
				if (companyId != null) {
					companyIds.add(companyId);
				}

			}
		} else {// 数据为空直接返回
			return new ArrayList<Premises>();
		}
		// 查询各个集合
		AreaDto areaDto = new AreaDto();
		areaDto.setIds(areaIds);
		List<Area> areas = areaMapper.selectListByDto(areaDto);
		for (Area a : areas) {
			areaMap.put(a.getId(), a);
		}

		CompanyDto companyDto = new CompanyDto();
		companyDto.setIds(companyIds);
		List<CompanyDto> companies = companyMapper.selectListByIds(companyDto);
		for (Company c : companies) {
			companyMap.put(c.getId(), c);
		}

		// 查询城市
		if (null != rows && rows.size() > 0) {
			for (Premises premises : rows) {
				Long areaId = premises.getAreaId();
				Long cityId = premises.getCityId();
				Long provId = premises.getProvinceId();
				if(provId != null) {
					Area area = areaMap.get(provId);
					premises.setProvName(area == null? null: area.getName());
				}
				if(cityId != null) {
					Area area = areaMap.get(cityId);
					premises.setCityName(area == null? null: area.getName());
				}
				if(areaId != null) {
					Area area = areaMap.get(areaId);
					premises.setAreaName(area == null? null: area.getName());
				}else {
					areaId = cityId;
				}
				
				if (areaId != null) {
					Area area = areaMap.get(areaId);
					if (area != null) {
						premises.setArea(area);
						premises.setFullAreaName(area.getFullName());
					} else {
						premises.setArea(new Area());
					}
				}
				premises.setPremisesStatusCN(PremisesStatusEnum.getByNo(premises.getPremisesStatus()).getDes());
				// 查询商户
				Company company = companyMap.get(premises.getCompanyId());
				premises.setCompanyName(company == null ? "" : company.getCompanyName());
			}
		}

		return rows;
	}

	/**
	 * 审核楼盘，变更分销商
	 * 
	 * @param entity
	 * @return
	 */
	@Override
	public int audit(PremisesDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.audit(entity);
	}

	/**
	 * 改变楼盘上下架状态
	 */
	@Override
	public int changeShelvesStatus(PremisesDto entity) {
		entity.setUpdateTime(Calendar.getInstance().getTime());
		return mapper.changeShelvesStatus(entity);
	}

	/**
	 * 对外分销楼盘
	 */
	@Override
	public Page<PremisesDto> getOutsidePremisesPage(PremisesDto premisesDto, int begin, int end) {
		Integer total = mapper.outsidePremisesCount(premisesDto);
		List<PremisesDto> rows = mapper.outsidePremisesList(premisesDto, begin, end);
		Page<PremisesDto> msr = new Page<PremisesDto>(total, rows);
		return msr;
	}

	/**
	 * 增加默认城市
	 * 
	 * @param currentCity
	 * @return
	 */
	public CityGroupDto getCurrentCity(String currentCity) {
		CityGroupDto dto = new CityGroupDto();
		List<PremisesCityDto> arraylist = new ArrayList<>();
		if (!StringUtils.isEmpty(currentCity)) {
			List<Area> areaList = areaMapper.selectAreaByHanZi(currentCity);
			if (CollectionUtils.isNotEmpty(areaList)) {
				Area area = areaList.get(0);
				dto.setCityFirEn("0");
				PremisesCityDto city = new PremisesCityDto();
				city.setCityUuid(area.getId().toString());
				city.setCityName(area.getName());
				city.setPinyin(currentCity);
				arraylist.add(city);
				dto.setPremisesVos(arraylist);
				return dto;
			}
		}
		return null;
	}

	@Override
	public List<CityGroupDto> getPremisesCityList(String currentCity) {
		List<CityGroupDto> list = new ArrayList<>();
		List<PremisesCityDto> cityList = mapper.selectPremisesCity();
		if (cityList != null && !cityList.isEmpty()) {
			list = CityGroupUtils.getCityGroup(cityList);
			list.add(getCurrentCity(currentCity));
			return list.stream().filter(s -> s != null).sorted(Comparator.comparing(CityGroupDto::getCityFirEn))
					.collect(Collectors.toList());
		}
		return list;
	}

	@Override
	public List<CityGroupDto> getPremisesCityGroupByPinyin(String currentCity, PremisesDto premisesDto) {
		List<CityGroupDto> list = new ArrayList<>();
		List<PremisesCityDto> cityList = mapper.selectPremisesCityGroupByPinyin(premisesDto);
		if (cityList != null && !cityList.isEmpty()) {
			list = CityGroupUtils.getCityGroup(cityList);
			list.add(getCurrentCity(currentCity));
			return list.stream().filter(s -> s != null).sorted(Comparator.comparing(CityGroupDto::getCityFirEn))
					.collect(Collectors.toList());
		}
		return list;
	}

	/**
	 * 转换集合属性值
	 * 
	 * @param list
	 * @return
	 */
	public List<PremisesViewDto> convertProperty(List<PremisesViewDto> list) {
		if (list != null && !list.isEmpty()) {
			list.stream().forEach(item -> {
				if (!StringUtils.isEmpty(item.getOpeningTime())) {
					Date date = DateUtils.StringToDate(item.getOpeningTime(), DateStyle.YYYY_MM_DD.getValue());
					item.setOpeningTime(DateUtils.DateToString(date, DateStyle.YYYY_MM_DD.getValue()));
				}
				if (!StringUtils.isEmpty(item.getCodeName())) {
					List<Long> ids = new ArrayList<>();
					List<String> idsStr = Arrays.asList(item.getCodeName().split(REG));
					idsStr.forEach(items -> {
						ids.add(new Long(items));
					});
					List<BaseCodeValue> listCodeValue = baseCodeValueService.selectWithIds(ids);
					List<String> codeList = listCodeValue.stream().map(BaseCodeValue::getCodeName).collect(Collectors.toList());
					item.setCodeName(StringUtils.join(codeList, REG));
				}
				item.setSaleStatusCN(SaleStatusEnum.getSalesByNo(item.getSaleStatus()));
				item.setEstateType(EstateTypeEnum.getByIds(item.getEstateType()));
				CommissionJsonDto commission = CommissionJsonDto.toJSON(item.getCommission());
				item.setCommission(commission == null ? null : commission.getTypeValue());
				item.setUnit(commission == null ? null : commission.getType());
			});
			return list;
		}

		return list;
	}

	@Override
	public Page<PremisesViewDto> getPremisesViewList(PremisesExtDto query) {
		List<PremisesViewDto> list = mapper.selectPremisesListByDto(query);
		Integer total = mapper.selectPremisesCount(query);
		list = convertProperty(list);
		Page<PremisesViewDto> page = new Page<>(total, list);
		page.setPageSize(query.getPageSize());
		return page;
	}

    @Override
    public List<Premises> selectIdListByDto(PremisesDto entity) {
        return mapper.selectIdListByDto(entity);
    }
	@Override
	public List<Premises> getListByCaseMember(PremisesDto entity) {
		List<Premises> rows = mapper.getListByCaseMember(entity);
		return rows;
	}

	/**
	 * 设置主推楼盘
	 * @param entity
	 * @return
	 */
	@Override
	public int updateMainPushPremises(PremisesDto entity) {
		if(null == entity.getId()){
			throw new RuntimeException("楼盘id为空");
		}

		if(null == entity.getMainPush()){
			throw  new RuntimeException("主推状态不能为空");
		}
		//设置主推时间
		entity.setMainPushSettime(Calendar.getInstance().getTime());
		return mapper.updatePremisesMainPush(entity);
	}

    @Override
    public List<Premises> selectListForCaseMember(PremisesDto entity) {
        return mapper.selectListForCaseMember(entity);
    }

    @Override
    public List<Premises> selectIdListByMobileTemp(PremisesDto premisesDto) {
        return mapper.selectIdListByMobileTemp(premisesDto);
    }

    @Override
    public Premises getLastPremises(Long devCompanyId,Long agentCompanyId){
		return mapper.selectLastPremises(devCompanyId,agentCompanyId);
	}

    @Override
    public Premises getSimpleById(Long aLong) {
        return mapper.getSimpleById(aLong);
    }

    @Override
    public int updatePremisesForRepeatReport(List<Long> premisesIdList) {
        return mapper.updatePremisesForRepeatReport(premisesIdList);
    }

    @Override
    public int updatePremisesForNoRepeatReport(PremisesDto premisesDto) {
        return mapper.updatePremisesForNoRepeatReport(premisesDto);
    }

	@Override
	public int updatePremisesForCheckSwitch(List<Long> premisesIdList) {
		return mapper.updatePremisesForCheckSwitch(premisesIdList);
	}

	@Override
	public int updatePremisesForNoCheckSwitch(PremisesDto premisesDto) {
		return mapper.updatePremisesForNoCheckSwitch(premisesDto);
	}

	@Override
	public int updatePremisesForFreeAudit(List<Long> premisesIdList) {
		return mapper.updatePremisesForFreeAudit(premisesIdList);
	}

	@Override
	public int updatePremisesForNoFreeAudit(PremisesDto premisesDto) {
		return mapper.updatePremisesForNoFreeAudit(premisesDto);
	}

	@Override
	public Page<ReportInfo> getAgentPremisesList(PremisesDto entity, int begin, int pageSize) {
		int total = mapper.getAgentPremisesCount(entity);
		List<ReportInfo> list = mapper.getAgentPremisesList(entity, begin, pageSize);
		return new Page<>(total, list);
	}

	@Override
	public Boolean checkBindPremises(Long premisesId, PartnerInfo partnerInfo) {
		// 管理员一律视为绑定
		if (partnerInfo.getAccountType().equals(MechanismAccountTypeEnum.mechanism.getNo())) {
			return Boolean.TRUE;
		}
		// 判断是否驻场楼盘
		CaseMemberDto caseMemberDto = new CaseMemberDto();
		caseMemberDto.setPartnerId(partnerInfo.getId());
		caseMemberDto.setCompanyId(partnerInfo.getHigherid());
		caseMemberDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
		caseMemberDto.setPremisesId(premisesId);
		List<CaseMember> list = caseMemberService.selectListByDto(caseMemberDto);
		if (CollectionUtils.isNotEmpty(list) ) {
			return Boolean.TRUE;
		}
		// 判断是否项目总监或项目经理所属楼盘
		PremisesDto premisesDto = new PremisesDto();
		premisesDto.setId(premisesId);
		premisesDto.setMobileTemp(partnerInfo.getPhone());
		premisesDto.setCompanyId(partnerInfo.getHigherid());
		premisesDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
		// 项目经理或者渠道总监
		List<Premises> premisesListForManage = selectIdListByMobileTemp(premisesDto);
		if(CollectionUtils.isNotEmpty(premisesListForManage)){
			return Boolean.TRUE;
		}

		// 置业顾问关联的楼盘
		List<EstateAdviser> adviserList = estateAdviserMapper.selectListByPartner(partnerInfo.getId());
		if(CollectionUtils.isNotEmpty(adviserList)){
			List<Long> premisesIds = adviserList.stream().map(EstateAdviser::getPremisesId).collect(Collectors.toList());
			premisesDto = new PremisesDto();
			premisesDto.setPremisesIds(premisesIds);
			premisesDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
			List<Premises> adviserPremisesList = selectIdListByDto(premisesDto);
			if(CollectionUtils.isNotEmpty(adviserPremisesList)){
				return Boolean.FALSE;
			}
		}
		return Boolean.FALSE;
	}
	
	/**
	 * 检测楼盘是否绑定
	 */
	@Override
	public void checkBindPremises(List<Long> premisesIds, PartnerInfo partnerInfo, 
			List<Long> bindPremisesIds, List<Long> notBindPremiseIds) {
		// 管理员一律视为绑定
		if (partnerInfo.getAccountType().equals(MechanismAccountTypeEnum.mechanism.getNo())) {
			for (Long premisesId : premisesIds) {
				bindPremisesIds.add(premisesId);
			}
			return;
		}
		// 判断是否驻场楼盘
		CaseMemberDto caseMemberDto = new CaseMemberDto();
		caseMemberDto.setPartnerId(partnerInfo.getId());
		caseMemberDto.setCompanyId(partnerInfo.getHigherid());
		caseMemberDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
		List<CaseMember> list = caseMemberService.selectListByDto(caseMemberDto);
		if(CollectionUtils.isNotEmpty(list)) {
			for (Long premisesId : premisesIds) {
				for (CaseMember caseMember : list) {
					if(caseMember.getPremisesId().longValue() == premisesId.longValue()) {
						bindPremisesIds.add(premisesId);
						break;
					}
				}
			}
		}
			
		// 判断是否项目总监或项目经理所属楼盘
		PremisesDto premisesDto = new PremisesDto();
		premisesDto.setMobileTemp(partnerInfo.getPhone());
		premisesDto.setCompanyId(partnerInfo.getHigherid());
		premisesDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
		// 项目经理或者渠道总监
		List<Premises> premisesListForManage = selectIdListByMobileTemp(premisesDto);
		if(CollectionUtils.isNotEmpty(premisesListForManage)) {
			for (Long premisesId : premisesIds) {
				for (Premises premises : premisesListForManage) {
					if(premises.getId().longValue() == premisesId.longValue()) {
						bindPremisesIds.add(premisesId);
						break;
					}
				}
			}
		}

		// 置业顾问关联的楼盘
		List<EstateAdviser> adviserList = estateAdviserMapper.selectListByPartner(partnerInfo.getId());
		if(CollectionUtils.isNotEmpty(adviserList)){
			List<Long> premisesIdList = adviserList.stream().map(EstateAdviser::getPremisesId).collect(Collectors.toList());
			premisesDto = new PremisesDto();
			premisesDto.setPremisesIds(premisesIdList);
			premisesDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
			List<Premises> adviserPremisesList = selectIdListByDto(premisesDto);
			if(CollectionUtils.isNotEmpty(premisesListForManage)) {
				for (Long premisesId : premisesIds) {
					for (Premises premises : adviserPremisesList) {
						if(premises.getId().longValue() == premisesId.longValue()) {
							bindPremisesIds.add(premisesId);
							break;
						}
					}
				}
			}
		}
	}

	/**
	 * 检查报备的电话号码是否符合对应楼盘的报备方式
	 */
	@Override
	public boolean checkMobileByPremises(String mobile, Long premisesId) {
		String reportWay = getReportWay(premisesId);
		return ReportWayEnum.checkMobile(mobile, reportWay);
	}
	
	/**
	 * 根据楼盘转换报备号码
	 * @param mobile
	 * @param premisesId
	 * @return
	 */
	@Override
	public String convertMobileByPremises(String mobile, Long premisesId){
		if(StringUtils.isBlank(mobile) || Objects.isNull(premisesId) || mobile.contains(StringConstant.THREE_STAR)){
			return mobile;
		}
		String reportWay = getReportWay(premisesId);
		if(!StringUtil.isNotNull(reportWay)) {
			return reportWay;
		}
		return ReportWayEnum.convertMobileByReportWay(mobile, reportWay);
	}
	
	/**
	 * 获取楼盘的报备方式
	 * @param premisesId
	 * @return
	 */
	@Override
	public String getReportWay(Long premisesId) {
		String premisesReportWayKey = RedisKeyConstant.Premises.PREMISES_REPORT_WAY_ + premisesId;
		Object object = RedisUtil.get(premisesReportWayKey);
		String reportWay = String.valueOf(object);
		if(StringUtil.isNotNull(reportWay)) {
			return reportWay;
		}
		Premises premises = mapper.selectSimpleById(premisesId);
		if(Objects.nonNull(premises)){
			reportWay = premises.getReportWay();
			RedisUtil.set(premisesReportWayKey, reportWay);
		}
		return reportWay;
	}

	@Override
	public List<SendPremisesResultDto> getSendPremisesList(String lastTime, Long companyId) {
		return mapper.getSendPremisesList(lastTime,companyId);
	}

}
